package com.wzq.solution;

import com.wzq.solution.node.ListNode;

class Solution24 {
    public static ListNode swapPairs(ListNode head) {
        
        ListNode newHead = null;
        ListNode tail = null;
        ListNode p1;
        while(head != null && head.next != null){
            p1 = head;
            head = head.next.next;
            if(newHead == null){
                newHead = p1.next;
            }else{
                tail.next = p1.next;
            }
            p1.next.next = p1;
            p1.next = null;
            tail = p1;
        }

        if(head != null){
            if(tail == null){
                newHead = head;
            }else{
                tail.next = head;
            }
        }
        return newHead;
        
    }

    public static void main(String[] args) {
        int[] headArr = new int[]{1,2,3,4};
        ListNode head = new ListNode(headArr[0]);
        ListNode p =head;
        for (int i=1;i<headArr.length; i++){
            p.next = new ListNode(headArr[i]);
            p = p.next;
        }
        swapPairs(head);
    }
}